package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.ContractProduct;
import cn.itcast.domain.cargo.ContractProductExample;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/cargo/contractProduct")
@Slf4j
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;

    /**
     * 查询列表
     * @param contractId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/list")
    public String list(String contractId,
                       @RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize){
        // A. 根据购销合同id查询货物
        //构造条件对象
         ContractProductExample example = new ContractProductExample();
         ContractProductExample.Criteria criteria = example.createCriteria();
         criteria.andContractIdEqualTo(contractId);
         PageInfo<ContractProduct> pageInfo = contractProductService.findByPage(example, pageNum, pageSize);


            //B。查询生产厂家
         FactoryExample factoryExample = new FactoryExample();
         FactoryExample.Criteria criteria1 = factoryExample.createCriteria();
         criteria1.andCtypeEqualTo("货物");
         List<Factory> factoryList = factoryService.findAll(factoryExample);

         //保存
        request.setAttribute("pageInfo",pageInfo);
        request.setAttribute("factoryList",factoryList);
        // 保存购销合同id，为了下一步点击保存货物时候拿到购销合同id
        //并且在保存的表单，有一个隐藏域的input，是关于contractId的
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-list";
    }

    @Autowired
    private FileUploadUtil fileUploadUtil;
    /**
     * 2. 货物添加、修改
     * 货物图片：<input type="file" name="productPhoto" >
     */
    @RequestMapping("/edit")
        public String edit(ContractProduct contractProduct,MultipartFile productPhoto){
        // 设置企业id、企业名称（后期再从登陆购销合同哪里获取）
        contractProduct.setCompanyId(getLoginCompanyId());
        contractProduct.setCompanyName(getLoginCompanyName());
        // 根据id判断是添加还是修改
        if (StringUtils.isEmpty(contractProduct.getId())) {
            if(productPhoto!=null){
                try {
                    //上传文件，获取上传文件的完整路径
                    String url = "http://" + fileUploadUtil.upload(productPhoto);
                    //保存对象的上传的图片路径
                    contractProduct.setProductImage(url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            contractProductService.save(contractProduct);
        } else {
            contractProductService.update(contractProduct);
        }
        return "redirect:/cargo/contractProduct/list?contractId="+contractProduct.getContractId();
        }

        @RequestMapping("/toUpdate")
        public String toUpdate(String id){
            //根据货物id查询，进行回显
             ContractProduct contractProduct = contractProductService.findById(id);

             //修改页面需要用到厂家，所以需要查询厂家
             FactoryExample factoryExample = new FactoryExample();
             FactoryExample.Criteria criteria = factoryExample.createCriteria();
             criteria.andCtypeEqualTo("货物");
             List<Factory> factoryList = factoryService.findAll(factoryExample);

            //保存数据
            //回显货物
            request.setAttribute("contractProduct",contractProduct);
            //工回显
            request.setAttribute("factoryList",factoryList);

            return "cargo/product/product-update";
        }

        @RequestMapping("/delete")
    public String delete(String id , String contractId){
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list?contractId="+contractId;
    }

    @RequestMapping("/toImport")
    public String toImport(String contractId){
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }

    @RequestMapping("/import")
    public String importExport(String contractId, MultipartFile file) throws IOException {
        //创建工作簿
         XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        //2. 获取工作表
        //getsheetAt(0)方法可以获取到excel的第一个sheet页
         XSSFSheet sheet = workbook.getSheetAt(0);
        //3. 获取总行数
         int rows = sheet.getPhysicalNumberOfRows();
         //4.遍历行，从第二行开始遍历
        for (int i = 0; i < rows; i++) {
                //4.1获取行对象
             XSSFRow row = sheet.getRow(i);

             //4.2创建货物对象，并将列的数据封装到对象中
            ContractProduct contractProduct = new ContractProduct();
            contractProduct.setFactoryName(row.getCell(1).getStringCellValue());
            contractProduct.setProductNo(row.getCell(2).getStringCellValue());
            contractProduct.setCnumber((int) row.getCell(3).getNumericCellValue());
            contractProduct.setPackingUnit(row.getCell(4).getStringCellValue());
            contractProduct.setLoadingRate(row.getCell(5).getNumericCellValue()+"");
            contractProduct.setBoxNum((int) row.getCell(6).getNumericCellValue());
            contractProduct.setPrice(row.getCell(7).getNumericCellValue());
            contractProduct.setProductDesc(row.getCell(8).getStringCellValue());
            contractProduct.setProductRequest(row.getCell(9).getStringCellValue());
            //【因为execl中没有，所有需要设置购销合同id】
            contractProduct.setContractId(contractId);
            //设置厂家id,通过表格的厂家名称，再获得厂家，在进而设置厂家id
             Factory factory = factoryService.findByName(contractProduct.getFactoryName());
             if(factory!=null){
                 contractProduct.setFactoryId(factory.getId());
             }
             //4.3给购销合同添加货物
            contractProductService.save(contractProduct);
        }

        return "redirect:/cargo/contract/list";
    }




}
